package com.xtwy.service;

import com.xtwy.entity.Menu;
import com.xtwy.entity.Role;
import com.xtwy.entity.User;
import com.xtwy.interceptor.MyGrantedAuthority;
import com.xtwy.repository.MenuRepository;
import com.xtwy.repository.UserRepository;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @作 者: 侯建军
 * @日 期: 2018/7/29 01:26
 * @描 述: 权限验证类
 * @公 司：山西迅腾伟业
 */
@Log
@Service
public class CustomUserService implements UserDetailsService {
    //自定义UserDetailsService 接口
    @Autowired
    UserRepository userRepository;
    @Autowired
    MenuRepository menuRepository;

    //重写loadUserByUsername 方法获得 userdetails 类型用户
    @Override
    public UserDetails loadUserByUsername(String username) {
//        User user = userRepository.findByUsername(username);
        User user = userRepository.findByUsername(username);
        //根据用户名获取用户id
        log.warning(username + "用户");
//        List<Object[]> list = userRepository.findByNameContaining(username);
        if (null != user) {
            List<Map> list = menuRepository.findByUserId(user.getId());
            List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
            if (list.size() > 0) {
                //存放授权信息

                //用于添加用户的权限。把用户角色添加到authorities。
                for (Map map : list) {
//                    //将权限加入授权中，注意权限格式以ROLE_开始，例ROLE_ADMIN
//                    authorities.add(new SimpleGrantedAuthority(objs[1].toString()));
//                    log.warning(objs[1].toString());
//                    user.setPassword(objs[3].toString());
                    GrantedAuthority grantedAuthority = new MyGrantedAuthority(map.get("url").toString(), map.get("method").toString());
                    grantedAuthorities.add(grantedAuthority);
                }
            }
            //返回用户授权信息
            return new org.springframework.security.core.userdetails.User(username,
                    user.getPassword(), grantedAuthorities);
        } else {
            throw new UsernameNotFoundException("用户名不存在");
        }
    }
}
